<template>
  <el-container :style="{cursor: submitting ? 'wait' : 'initial'}">
    <canvas class="background"></canvas>

    <el-main>
      <div class="login-container">
        <div class="title">
          <span class="main-title">{{APP_NAME}}</span>
          <div class="sub-title">欢迎登录</div>
        </div>
        <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-width="0px"
          size="large"
        >
          <el-form-item prop="username">
            <el-input
              ref="username"
              v-model="form.username"
              placeholder="用户名"
              tabindex="1"
              clearable
              @clear="clear('username')"
              @change="onUsernameChange"
              @keydown.enter.native="onSubmit">
              <el-button slot="prepend" icon="el-icon-user"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              ref="password"
              v-model="form.password"
              type="password"
              placeholder="密码"
              tabindex="2"
              clearable
              autocomplete="new-password"
              @clear="clear('password')"
              @focus="onPasswordFocus"
              @keydown.enter.native="onSubmit">
              <el-button slot="prepend" icon="el-icon-lock"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item class="checkboxes">
            <el-checkbox
              v-model="autoLoginEnabled"
              tabindex="3"
              @change="onAutoLoginChange">自动登陆</el-checkbox>
            <el-checkbox
              v-model="rememberPasswordEnabled"
              style="float: right;"
              tabindex="4"
              @change="onRememberPasswordChange">记住密码</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              style="width: 100%;"
              tabindex="5"
              :disabled="!(form.username && form.password)"
              :loading="submitting"
              @click="onSubmit"
            >
              <span style="letter-spacing: 4px;">登录</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-main>
    <el-footer style="text-align:center;">
      <el-link
        type="info"
        :underline="false"
        target="_blank"
        href="http://www.loveonline.net.cn/about-us.html"
      >Copyright ©{{ moment().year() }} 武汉亲情互联科技有限公司</el-link>
    </el-footer>
  </el-container>
</template>

<script>
import config, { APP_NAME } from '@/config/app.config';
import session from '@/auth/session';
import moment from 'moment';
import particlesjs from 'particlesjs';

export default {
  data() {
    this.moment = moment;
    this.APP_NAME = APP_NAME;
    
    return {
      autoLoginEnabled: config.get('autoLoginEnabled'),
      rememberPasswordEnabled: config.get('rememberPasswordEnabled'),
      form: {
        username: config.get('username'),
        password: config.get('password')
      },
      needClearPassword: false,
      submitting: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'submit' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'submit' }
        ]
      }
    };
  },
  watch: {
    submitting(val) {
      this.background[val ? 'pauseAnimation' : 'resumeAnimation']();
    }
  },
  mounted() {
    this.initBackground();

    document.querySelectorAll('.el-input').forEach(el => {
      el.addEventListener('mouseleave', () => {
        ['username', 'password'].forEach((input) => {
          this.$refs[input].blur();
        });
      });
    });

    if (this.autoLoginEnabled && !window.fromLogout) {
      const username = config.get('username');
      const password = config.get('password');
      if (username && password) {
        setTimeout(() => {
          this.form = { username, password };
          this.$nextTick(() => {
            this.submit();
          });
        }, 100);
      }
    } else {
      for (let field of ['username', 'password']) {
        if (!this.form[field]) {
          this.$refs[field].focus();
          break;
        }
      }
    }

    var userAgent = navigator.userAgent;
    if (!(userAgent.indexOf("Firefox") > -1 || userAgent.indexOf("Chrome") > -1) || navigator.userAgent.indexOf("Edge") > -1) {
      this.$message.warning({
        message: `
          为了更好的体验，请优先使用这些浏览器：
          <a href="https://www.baidu.com/s?wd=Chrome"
              target="_blank" style="color: inherit;">GoogleChrome</a>
          或
          <a href="http://www.firefox.com.cn/"
              target="_blank" style="color: inherit;">Firefox</a>&nbsp;`,
        dangerouslyUseHTMLString: true,
        duration: 10000,
        showClose: true
      });
    }
  },
  destroyed() {
    this.background.destroy();
  },
  methods: {
    onUsernameChange() {
      this.needClearPassword = true;
    },
    onPasswordFocus() {
      if (this.needClearPassword) {
        this.form.password = '';
        this.needClearPassword = false;
      }
    },
    clear(field) {
      this.$refs[field].focus();
    },
    onAutoLoginChange(checked) {
      config.set('autoLoginEnabled', checked);
      if (checked) {
        this.rememberPasswordEnabled = true;
        config.set('rememberPasswordEnabled', true);
      }
    },
    onRememberPasswordChange(checked) {
      config.set('rememberPasswordEnabled', checked);
      if (!checked) {
        this.autoLoginEnabled = false;
        config.set('autoLoginEnabled', false);
        config.set('password', '');
      }
    },
    onSubmit() {
      this.$refs.form.validate( (valid, errors) => {
        if (!valid) {
          for (let field of ['username', 'password']) {
            if (errors[field]) {
              this.$refs[field].focus();
              break;
            }
          }
          return;
        }

        this.submit();
      });
    },
    async submit() {
      const { username, password } = this.form;
      this.submitting = true;
      const ret = await this.$http.post('api/admin/login', {username, password, permissions: true}).catch(error => {
        this.$message.error('登录失败！');
        this.submitting = false;
      });
      if (!ret) return;
      if (ret.success) {
        config.set('username', username);
        config.set('password', this.rememberPasswordEnabled ? password : '');    
        session.login(ret.data.admin);
        this.$router.replace('/');
      } else {
        config.set('password', '');
        this.$message.error(ret.message);
        this.submitting = false;
      }
    },
    initBackground() {
      this.background = particlesjs.init({
        selector: '.background',
        color: '#d0d4dd',
        maxParticles: 150,
        sizeVariations: 6,
        speed: 0.3,
        connectParticles: true,
        responsive: [
          {
            breakpoint: 768,
            options: {
              maxParticles: 80
            }
          }, {
            breakpoint: 375,
            options: {
              maxParticles: 50
            }
          }
        ]
      });

      ['username', 'password'].forEach((field) => {
        this.$refs[field].$on('input', () => {
          this.background.pauseAnimation();
        });
        this.$refs[field].$on('blur', () => {
          this.background.resumeAnimation();
        });
      });
    }
  }
}
</script>

<style scoped>
.background {
  position: absolute;
  display: block;
  top: 0;
  left: 0;
  z-index: 0;
}

.el-main {
  -ms-flex-align: center;
  -ms-flex-item-align: center;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  position: relative;
  z-index: 1;
}
.el-container {
  width: 100%;
  height: 100%;
}

.title {
  text-align: center;
  margin-bottom: 22px;
}

.main-title {
  font-size: 26px;
  color: #222;
  letter-spacing: 4px;
}
.sub-title {
  font-size: 14px;
  padding-top: 8px;
  color: #606266;
  letter-spacing: 2px;
}

.login-container {
  width: 320px;
}
.checkboxes {
  position: relative;
  top: -10px;
  height: 20px;
}
.el-checkbox {
  font-weight: normal;
}

.el-button--primary {
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}

.el-link {
  font-weight: unset;
}
</style>